package com.WISSC.util.file;

import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Date;

/**
 * <p>
 *
 * </p>
 *
 * @author 张凯
 * @since 2019/6/17
 */
public class FilePath {

    public static String getPath(String fileName) throws FileNotFoundException {
        //String path = "F:/test" ;
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        //System.out.println("path:"+path);
        String filePath = path.getParentFile().getParentFile() + File.separator + "uploads" + File.separator;
        //System.out.println("filePath:"+filePath);
        String fiilePath = getJarRootPath() + "/uploads/" + new Date().getTime() + fileName;
        //System.out.println("fiilePath:"+fiilePath);
        fiilePath = fiilePath.replace('\\', '/');
        return fiilePath;
    }

    private static String getJarRootPath() throws FileNotFoundException {
        String path = ResourceUtils.getURL("classpath:").getPath();
        //=> file:/root/tmp/demo-springboot-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/
        //System.out.println("ResourceUtils.getURL(\"classpath:\").getPath() -> "+path);
        //创建File时会自动处理前缀和jar包路径问题 => /root/tmp
        File rootFile = new File(path);
        if (!rootFile.exists()) {
            rootFile = new File("");
        }
        //获取的字符串末尾没有分隔符 /
        return rootFile.getAbsolutePath();
    }
}
